package data_structure;

import java.util.Comparator;
import java.util.PriorityQueue;

public class leetcode_0023 {
    public ListNode mergeKLists(ListNode[] lists) {
        if(lists.length==0) return null;
        ListNode head = new ListNode();
        ListNode p = head;
        PriorityQueue<ListNode> priorityQueue = new PriorityQueue<>(new Comparator<ListNode>() {
            @Override
            public int compare(ListNode o1, ListNode o2) {
                return o1.val-o2.val;
            }
        });
        for(ListNode listNode: lists){
            if(listNode !=null){
                priorityQueue.add(listNode);
            }
        }
        while(priorityQueue.size()>0){
            ListNode node = priorityQueue.poll();
            p.next=node;
            if(node.next!=null){
                priorityQueue.add(node.next);
            }
            p=p.next;
        }
        p.next=null;
        return head.next;
    }
}
